<template>
	<a-modal v-bind="options" class="house-detail-dialog">
		<template #title>{{ value.houseFullAddress }}</template>
		<a-tabs v-model:active-key="activeTab" tab-position="left" @change="onTabChange">
			<a-tab-pane key="basic" tab="基本信息">
				<template v-if="value.houseType === 2">
					<house-room-cards v-model:value="currentHouse" :rooms="houseRooms" :loading="loadings.load" />
				</template>
				<house-room-detail :value="currentHouse" @getApprovalStatus="getApprovalStatus" />
			</a-tab-pane>
			<a-tab-pane key="contract" tab="合约管理" v-if="hasPermissions(['mk_contract_reserve', 'mk_contract_renter'])">
				<template v-if="value.houseType === 2">
					<house-room-cards v-model:value="currentHouse" :rooms="houseRooms" :loading="loadings.load" />
				</template>
				<a-tabs class="inner-tabs" size="small" destroy-inactive-tab-pane v-model:active-key="contractTabsKey">
					<template #rightExtra>
						<a-space>
							<template v-if="currentHouse.houseStatus === 11 && hasPermissions(['mk_contract_reserve_yd'])">
								<a-button type="primary" ghost size="small" @click="signRenterReserve">租客预定</a-button>
							</template>
							<template v-if="[11, 20].includes(currentHouse.houseStatus) && hasPermissions(['mk_contract_tenant_tjzkht'])">
								<a-button type="primary" ghost size="small" @click="signRenterContract">租客签约</a-button>
							</template>
							<template
								v-if="value.houseBizMode == 1 && !value.ownerContractId && hasPermissions(['mk_contract_owner_yzqy'])">
								<a-button type="primary" ghost size="small" @click="signOwnerContract">业主签约</a-button>
							</template>
						</a-space>
					</template>
					<a-tab-pane key="reserve" tab="租客预定" v-if="hasPermissions(['mk_contract_reserve'])">
						<reserve :query="bizQuery" source="house" :search-container="false" />
					</a-tab-pane>
					<a-tab-pane key="tenant" tab="租客合同" v-if="hasPermissions(['mk_contract_renter'])">
						<tenant :query="bizQuery" source="house" :search-container="false" />
					</a-tab-pane>
					<a-tab-pane key="owner" tab="业主合同" v-if="hasPermissions(['mk_contract_owner']) && value.houseBizMode == 1">
						<owner :query="bizQuery" source="house" :search-container="false" />
					</a-tab-pane>
				</a-tabs>
			</a-tab-pane>
			<a-tab-pane
				key="finance"
				tab="财务账单"
				v-if="hasPermissions(['mk_contract_finance_bill', 'mk_finance_bill_detail', 'mk_finance_bill_flow'])">
				<template v-if="value.houseType === 2">
					<house-room-cards v-model:value="currentHouse" :rooms="houseRooms" :loading="loadings.load" />
				</template>
				<bill-tabs
					:isValid="true"
					v-if="bizQuery.houseId || bizQuery.housePid"
					:query="bizQuery"
					source="house"
					:approvalStatus="approvalStatus" />
			</a-tab-pane>

			<a-tab-pane key="device" tab="智能设备" v-if="hasPermissions(['mk_device'])">
				<div id="device_container" class="overFlow-y"></div>
			</a-tab-pane>

			<a-tab-pane
				key="workorder"
				tab="租后服务"
				v-if="hasPermissions(['mk_workorder_repair', 'mk_workorder_cleaning', 'mk_workorder_complaint'])">
				<template v-if="value.houseType === 2">
					<house-room-cards v-model:value="currentHouse" :rooms="houseRooms" :loading="loadings.load" @change="onTabChange" />
				</template>
				<a-tabs id="workorder_tab" v-model:active-key="activeWorkorder" class="inner-tabs" size="small" @change="onTabChange">
					<template #rightExtra>
						<div id="house_workorder_search" />
					</template>
					<a-tab-pane key="/repair" tab="维修" v-if="hasPermissions(['mk_workorder_repair'])" />
					<a-tab-pane key="/cleaning" tab="保洁" v-if="hasPermissions(['mk_workorder_cleaning'])" />
					<a-tab-pane key="/complaint" tab="投诉" v-if="hasPermissions(['mk_workorder_complaint'])" />
				</a-tabs>
			</a-tab-pane>

			<a-tab-pane key="enterprise" tab="资产管理" v-if="hasPermissions(['mk_enterprise'])">
				<template v-if="value.houseType === 2">
					<house-room-cards v-model:value="currentHouse" :rooms="houseRooms" :loading="loadings.load" @change="onTabChange" />
				</template>
				<div id="enterprise_container" class="enterprise-container-dialog"></div>
			</a-tab-pane>
		</a-tabs>
	</a-modal>

	<!-- 添加预定 -->
	<template v-if="visibles.reserve">
		<add-reserve-dialog v-model:visible="visibles.addReserve" :house-record="reserveData" />
	</template>
	<!-- 业主签约 -->
	<template v-if="visibles.owner">
		<owner-sign
			v-model:visible="visibles.ownerSign"
			:contract="{
				houseId: ownerHouseId,
				signType: 1
			}" />
	</template>
	<!-- 租客签约 -->
	<template v-if="visibles.renterContract">
		<signing-dialog v-model:visible="visibles.addRenterContract" :contract="signData" :signing-type="'renter'" />
	</template>
</template>

<script lang="ts" setup>
	import {computed, nextTick, reactive, ref, toRaw, toRef, watchEffect, watch} from 'vue'
	import {HouseBase, HouseRoom} from '@/interface/house'
	import houseApi from '@/api/house-api'
	import HouseRoomCards from '@/components/house/detail/house-room-cards.vue'
	import HouseRoomDetail from '@/components/house/detail/house-room-detail.vue'
	import Reserve from '@/pages/contract/reserve'
	import Tenant from '@/pages/contract/tenant'
	import Owner from '@/pages/contract/owner'
	import AddReserveDialog from '@/components/contract/add-reserve-dialog'
	import {microApps} from '@/micros/apps'
	import {useStore} from '@/store'
	import RenterSignDialog from '@/components/contract/tenant/renter-sign-dialog.vue'
	import {RenterContract} from '@/interface/contract'
	import BillTabs from '@/components/finance/bill-tabs.vue'

	const hasPermissions = useStore().hasPermissions

	const props = defineProps<{
		visible: boolean
		value: HouseBase
		active?: string
	}>()

	const visibles = reactive({
		addReserve: false,
		addRenterContract: false,
		ownerSign: false,
		owner: false,
		renterContract: false,
		reserve: false
	})

	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		width: '90%',
		header: null,
		footer: null,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			houseRooms.value = []
			// 卸载子应用
			visibles.owner = false
			visibles.renterContract = false
			visibles.reserve = false
			microApps.removeAll()
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const activeTab = ref<string>('contract')
	const contractTabsKey = ref<string>('tenant')
	const activeWorkorder = ref<string>('/repair')
	const currentHouse = ref<HouseBase>({})
	const houseRooms = ref<HouseRoom[]>([])
	const approvalStatus = ref('')
	const ownerHouseId = ref<any>()
	// 业务查询
	const bizQuery = computed(() => {
		const query: any = {
			order: 'asc',
			houseId: currentHouse.value.id,
			tabListType: 'hide'
		}
		if (currentHouse.value.houseType === 2 && currentHouse.value.id === currentHouse.value.housePid) {
			query.houseId = undefined
			query.housePid = currentHouse.value.housePid
		}

		return query
	})

	const loadings = reactive({
		save: false,
		load: false
	})
	// 获取房源下子间房间列表
	const getHouseRooms = () => {
		loadings.load = true
		houseApi
			.houseRooms(props.value.housePid as string)
			.then(({data = []}) => {
				// 审批状态的字段
				houseRooms.value = data
				currentHouse.value = data.find(o => o.id === props.value.id)
			})
			.finally(() => (loadings.load = false))
	}

	watch(
		() => props.visible,
		() => {
			if (props.visible) {
				microApps.removeAll()
				currentHouse.value = props.value
				activeTab.value = props.active || 'contract'
				nextTick(onTabChange)
				ownerHouseId.value = currentHouse.value.id
				if (props.value.houseType === 2) {
					// 合租获取所有房间
					ownerHouseId.value = props.value.housePid
					getHouseRooms()
				}
			}
		}
	)

	// 预定房源数据
	const reserveData = computed(() => ({
		houseType: currentHouse.value.houseType,
		houseRoomId: currentHouse.value.id,
		houseBaseId: currentHouse.value.housePid,
		houseAddress: currentHouse.value.houseFullAddress
	}))

	// 预定签约数据
	const signData = ref<RenterContract>({})
	const signRenterReserve = () => {
		visibles.reserve = true
		let timeOut = setTimeout(() => {
			visibles.addReserve = true
			clearTimeout(timeOut)
		}, 150)
	}
	const signRenterContract = () => {
		if (currentHouse.value.id) {
			visibles.renterContract = true
			let timeOut = setTimeout(() => {
				signData.value = {
					signType: 1,
					houseId: currentHouse.value.id
				}

				visibles.addRenterContract = true
				clearTimeout(timeOut)
			}, 150)
		}
	}
	const signOwnerContract = () => {
		visibles.owner = true
		let timeOut = setTimeout(() => {
			visibles.ownerSign = true
			clearTimeout(timeOut)
		}, 150)
	}
	const onTabChange = () => {
		// console.log(currentHouse.value)
		switch (activeTab.value) {
			case 'device':
				microApps.loadApp({
					name: activeTab.value,
					props: {
						path: '/house-devices',
						query: {
							id: currentHouse.value.id,
							housePid: currentHouse.value.housePid,
							houseAddress: currentHouse.value.houseFullAddress
						}
					},
					container: '#device_container'
				})
				return

			case 'workorder':
				microApps.loadApp({
					name: activeTab.value,
					props: {
						path: activeWorkorder.value,
						query: bizQuery.value,
						searchContainer: '#house_workorder_search'
					},
					container: '#workorder_tab .ant-tabs-content-holder'
				})
				return

			case 'enterprise':
				microApps.loadApp({
					name: activeTab.value,
					props: {
						path: '/house/assets',
						searchContainer: '#asset_tab_right_search',
						query: {
							source: 'house',
							houseId: bizQuery.value.houseId,
							parentHouseId: bizQuery.value.housePid,
							houseAddress: currentHouse.value.houseFullAddress
						}
					},
					container: '#enterprise_container'
				})

				return

			default:
				return
		}
	}

	const getApprovalStatus = data => {
		console.log(data)
		approvalStatus.value = data
	}
</script>

<style lang="less">
	.house-detail-dialog {
		max-width: 1600px;
		overflow: hidden;

		.ant-modal-body {
			padding: 0;
			height: 80vh;
			overflow: auto;
			min-height: 600px;
			max-height: 1000px;

			> .ant-tabs {
				height: 100%;

				.ant-tabs-content,
				.ant-tabs-content-holder {
					height: 100%;
				}

				#device_container,
				#enterprise_container {
					height: 100%;
				}

				.ant-tabs-content-left > .ant-tabs-tabpane {
					overflow: auto;
					padding: 8px 16px;

					//&:not(:first-child) {
					//	display: flex;
					//	flex-direction: column;
					//}
				}
			}

			.inner-tabs {
				height: 100%;

				#house_workorder_search {
					width: 600px;
				}

				> .ant-tabs-nav {
					margin-bottom: 0;
				}

				> .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane {
					padding: 0;
				}
			}
		}

		.enterprise-container-dialog {
			.vxe-toolbar .vxe-buttons--wrapper,
			.vxe-toolbar .vxe-tools--wrapper {
				flex-wrap: nowrap;
				width: 40%;
			}

			#asset_tab_right_search {
				margin-left: 15px;
			}
		}
	}
</style>
